package com.example.service.impl;

import com.example.dao.BookShopDao;
import com.example.service.BookShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: overer
 * @description:
 * @author: 诸葛龙辰
 * @create: 2022-11-14 21:12
 **/
@Service
public  class BookShopServiceImpl extends BookShopService {
    @Autowired
    private BookShopDao bookShopDao;

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED,
            timeout = 1
    )
    public void purchase(String isbn, String username) {
        /**开启事务
         * 根据图书编号查询图书对应的价格
         *
         */

        int price = bookShopDao.findBookPriceByIsbn(isbn);
        //判断库存是否够
        int stock = bookShopDao.findStockByIsbn(isbn);
        if (stock > 0) {
            // 修改库存
            bookShopDao.updateBookStock(isbn);
        } else {
            throw new RuntimeException("图书编号为:" + isbn + ";库存不足");
        }
        try {
            //延迟
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //判断余额是否够
        int balance = bookShopDao.findBalanceByUsername(username);
        if (balance >= price) {
            // 修改账户余额
            bookShopDao.updateAccount(username, price);
        } else {
            throw new RuntimeException("账户为:" + username + ";余额不足.");
        }

    }

}
